package com.thx.app.remote.impl;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import mixedserver.protocol.RPCException;
import mixedserver.protocol.SessionAttributes;
import mixedserver.protocol.SessionRelatedModul;
import mixedserver.protocol.jsonrpc.JsonRpcSessionAttributes;
import mixedserver.protocol.jsonrpc.client.Client;

import org.apache.commons.lang3.StringUtils;

import com.thx.app.remote.UserInterface;
import com.thx.app.remote.model.RPCExceptionCode;
import com.thx.app.remote.model.RPCResponse;
import com.thx.app.remote.model.User_;
import com.thx.app.remote.util.UserUtil;
import com.thx.app.remote.util.UserUtil.SaveOtherListener;
import com.thx.app.remote.util.UserUtil.ValidateListener;
import com.thx.common.spring.BeanFactory;
import com.thx.common.web.WebConstant;
import com.thx.file.util.WebFileUtil;
import com.thx.log.LogUtil;
import com.thx.user.model.User;
import com.thx.user.service.UserManager;

public class UserImp implements UserInterface, SessionRelatedModul {
	private JsonRpcSessionAttributes session;
	UserManager userManager = (UserManager) BeanFactory.getBean("userManager");

	public RPCResponse login(final String userName, String pwd,
			final String validator, final String deviceId, final String imsi)
			throws RPCException {
		
		RPCResponse response = new RPCResponse();
		try {
			response = UserUtil.login(session,userName, pwd, validator,new ValidateListener() {
						public void checkout() throws RPCException {
							
						}
					}, new SaveOtherListener() {
						public void saveAttribute(HttpServletRequest request,RPCResponse b) {
							UserUtil.updateDeviceId(userName, deviceId, imsi);
						}
					});
			LogUtil.log("客户端", LogUtil.ACTION_LOGIN, LogUtil.RESULT_SUCCESS, "RPC登录成功");
		} catch (RPCException e) {
			LogUtil.log("客户端", LogUtil.ACTION_LOGIN, LogUtil.RESULT_SUCCESS, "RPC登录失败#"+e.getMessage());
			throw new RPCException(e.getMessage(),e.getCode());
		}
		return response;
	}

	public RPCResponse loadUserSearch(String userName) throws RPCException {
		RPCResponse response = new RPCResponse();
		try {
			User u = userManager.findByName(userName);
			if (u != null) {
				response.setAttribute("username", userName);
				response.setAttribute("userid", u.getUserId() + "");
			}
			return response;
		} catch (Exception e) {
			e.printStackTrace();
		}

		throw new RPCException("该用户不存在",RPCExceptionCode.OPERATION_EXCEPTIONCODE);
	}

	public boolean saveUserInfor(User_ user) throws RPCException {
		return UserUtil.saveUserInfor(user);
	}

	public String getCaptcha(String deviceId, String simCardId) throws RPCException {
		return UserUtil.getCaptcha(session,deviceId, simCardId);
	}

	public boolean sendSmsVerifyCode(String phoneNumber, String captcha,
			String deviceId, String simCardId) throws RPCException {
		return false;
	}

	public void setSession(SessionAttributes session) {
		this.session = (JsonRpcSessionAttributes) session;

	}

	public static void main(String[] args) {
		Client client = Client.getClient("http://localhost:8080/thx-web-simple/JSON-RPC?debug=true");
		client.setDencryptMessage(true);
		UserInterface d = (UserInterface) client.openProxy("user",UserInterface.class);
		try {
			// System.out.println(d.getCaptcha());
			/*
			 * User_ u =new User_(); u.setPassword(2+""); u.setUserName("99");
			 * d.saveUserInfor(u);
			 */
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 修改密码
	 */
	public String changePassword(String userName, String oldPwd, String newPwd) throws RPCException {
		HttpServletRequest request = UserUtil.getRequest();
		UserUtil.ValidateSession(request); //验证用户session是否有效 
		
		String msg = UserUtil.changePassword(userName,oldPwd, newPwd);
		if(msg.equals("")){
			LogUtil.log("客户端", "修改用户密码", LogUtil.RESULT_SUCCESS, "RPC 修改用户密码成功");
			return msg;
		}else{
			LogUtil.log("客户端", "修改用户密码", LogUtil.RESULT_SUCCESS, "RPC 修改用户密码失败");
			return msg;
		}
	}

	/**
	 * 注销用户
	 */
	public boolean logOut() throws RPCException {
		return UserUtil.logOut(session);
	}

	public RPCResponse getLoadUserInfor(String pluginCode) throws RPCException {
		HttpServletRequest request = UserUtil.getRequest();
		UserUtil.ValidateSession(request); //验证用户session是否有效 
		
		RPCResponse response = new RPCResponse();
		User user = (User)request.getSession().getAttribute(WebConstant.KEY_RPC_USER);
		response.setAttribute(UserInterface.SK_USERID, user.getUserId());
		response.setAttribute(UserInterface.SK_USERNAME, user.getUserName());
		response.setAttribute(UserInterface.SK_REALNAME, user.getRealName());
		response.setAttribute(UserInterface.SK_DEPID, user.getDepartment().getDepId());
		response.setAttribute(UserInterface.SK_DEPNAME, user.getDepartment().getDepName());
		response.setAttribute(UserInterface.SK_USERLOGO, user.getUserLogo()==null?"":user.getUserLogo());
		
		return response;
	}

	/**
	 * 保存用户头像信息
	 */
	public String sendUserImage(byte[] picStream) throws RPCException {
		HttpServletRequest request = UserUtil.getRequest();
		UserUtil.ValidateSession(request); //验证用户session是否有效 
		
		User user = (User)request.getSession().getAttribute(WebConstant.KEY_RPC_USER);
		com.thx.file.model.File file = WebFileUtil.uploadAndSaveFile(user.getUserId()+".jpg", picStream);
		if(StringUtils.isNotBlank(file.getFileId())){
			User newUser = userManager.get(user.getUserId());
			newUser.setUserLogo(file.getFileId());
			newUser.setLastUpdateDate(new Date());
			userManager.save(newUser);
			
			user.setUserLogo(file.getFileId());
			session.setAttribute(WebConstant.KEY_RPC_USER, user); 
			request.getSession().setAttribute(WebConstant.KEY_RPC_USER, user);
			return file.getFileId();
		}else{
			return "";  
		}
	}

	public boolean updatePwd(String mobile, String newPwd) throws RPCException {
		// TODO Auto-generated method stub
		/**
		*方法说明:
		*@qhh
		*@2015年1月8日下午3:14:34
		*/
		return false;
	}

	public String sendSmsStr(String phoneNumber, String reg)
			throws RPCException {
		// TODO Auto-generated method stub
		/**
		*方法说明:
		*@qhh
		*@2015年1月26日上午11:56:39
		*/
		return null;
	}
}
